---
hide_table_of_contents: true
---

import CodeBlock from "@theme/CodeBlock";

# Astra DB Chat Memory

For longer-term persistence across chat sessions, you can swap out the default in-memory `chatHistory` that backs chat memory classes like `BufferMemory` for Astra DB.

## Setup

You need to install the Astra DB TS client:

```bash npm2yarn
npm install @datastax/astra-db-ts
```

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash npm2yarn
npm install @langchain/openai @langchain/community
```

## Configuration and Initalization

There are two ways to inialize your `AstraDBChatMessageHistory`

If you already have an instance of the `AstraDB` client defined you can connect to your collection and initialize an instance of the `ChatMessageHistory` using the constuctor.

```typescript
const client = (client = new AstraDB(
  process.env.ASTRA_DB_APPLICATION_TOKEN,
  process.env.ASTRA_DB_ENDPOINT,
  process.env.ASTRA_DB_NAMESPACE
));

const collection = await client.collection("YOUR_COLLECTION_NAME");

const chatHistory = new AstraDBChatMessageHistory({
  collection,
  sessionId: "YOUR_SESSION_ID",
});
```

If you don't already have an instance of an `AstraDB` client you can use the `initialize` method.

```typescript
const chatHistory = await AstraDBChatMessageHistory.initialize({
  token: process.env.ASTRA_DB_APPLICATION_TOKEN ?? "token",
  endpoint: process.env.ASTRA_DB_ENDPOINT ?? "endpoint",
  namespace: process.env.ASTRA_DB_NAMESPACE,
  collectionName: "YOUR_COLLECTION_NAME",
  sessionId: "YOUR_SESSION_ID",
});
```

## Usage

:::tip Tip
Your collection must already exist
:::

import Example from "@examples/memory/astradb.ts";

<CodeBlock language="typescript">{Example}</CodeBlock>
